package com.iqilu.ksd.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.TVBean;
import com.iqilu.ksd.constant.RadioInfo;
import com.iqilu.ksd.utils.TVUtils;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Coofee on 2016/11/28.
 */

public class RadioService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

    private static final String TAG = "RadioService";

    private MediaPlayer mMediaPlayer;
    private Notification notification;
    private NotificationManager mNotificationManager;

    private ArrayList<TVBean> list;
    private TVBean tvBean;
    private int curRadioId;
    private String status;
    private boolean isRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        list = TVUtils.getRadioList();
        tvBean = list.get(0);
        curRadioId = tvBean.getId();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            if (intent.getAction().equals(RadioInfo.SERVICE_MEDIAPLAYER_PLAY)) {
                curRadioId = intent.getIntExtra(RadioInfo.CURRADIOID, tvBean.getId());
                tvBean = TVUtils.getRadioById(curRadioId);
                resetNotifyTitle();
                Log.i(TAG, "onStartCommand - PLAY");
                if (mMediaPlayer == null) {
                    setUpMediaPlayer(tvBean.getUrl());
                    generateNotification();
                } else {
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.stop();
                    }
                    try {
                        mMediaPlayer.reset();
                        mMediaPlayer.setDataSource(tvBean.getUrl());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mMediaPlayer.prepareAsync();
                }
                sendBroadcastEventStatus(RadioInfo.STATUS_PLAY);
            } else if (intent.getAction().equals(RadioInfo.SERVICE_MEDIAPLAYER_STOP)) {
                Log.i(TAG, "onStartCommand - STOP");
                if (mMediaPlayer != null) {
                    stopMediaPlayer();
                }
            } else if (intent.getAction().equals(RadioInfo.SERVICE_MEDIAPLAYER_STOPANDCLOSE)) {
                Log.i(TAG, "onStartCommand - STOPANDCLOSE");
                removeNotification();
                stopAndCloseMediaPlayer();
            } else if (intent.getAction().equals(RadioInfo.SERVICE_MEDIAPLAYER_LAST)) {
                playLast();
            } else if (intent.getAction().equals(RadioInfo.SERVICE_MEDIAPLAYER_NEXT)) {
                playNext();
            }
            resetNotifyButton(intent.getAction());
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new RadioBinder();
    }

    public class RadioBinder extends Binder {
        public RadioService getService() {
            return RadioService.this;
        }
    }

    public void setUpMediaPlayer(String url) {
        setRunning(true);
        try {
            mMediaPlayer = new MediaPlayer();
//            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        mMediaPlayer.release();
        mMediaPlayer = null;
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        setRunning(true);
    }

    private void playNext() {
        curRadioId++;
        if (curRadioId > 9) {
            curRadioId = 1;
        }
        Log.i(TAG, "playNext curRadioId=" + curRadioId);
        tvBean = TVUtils.getRadioById(curRadioId);
        reStartMediaPlayer();
        sendBroadcastEventStatus(RadioInfo.STATUS_NEXT);
        resetNotifyTitle();
    }

    private void playLast() {
        curRadioId--;
        if (curRadioId < 1) {
            curRadioId = 9;
        }
        tvBean = TVUtils.getRadioById(curRadioId);
        reStartMediaPlayer();
        sendBroadcastEventStatus(RadioInfo.STATUS_LAST);
        resetNotifyTitle();
    }

    public int getCurRadioId() {
        return curRadioId;
    }

    // 快捷按钮
    public void generateNotification() {
        if (Build.VERSION.SDK_INT < 11) {
            return;
        }
        Intent intentCloseAndStop = new Intent(this, RadioService.class);
        intentCloseAndStop.setAction(RadioInfo.SERVICE_MEDIAPLAYER_STOPANDCLOSE);

        Intent intentStop = new Intent(this, RadioService.class);
        intentStop.setAction(RadioInfo.SERVICE_MEDIAPLAYER_STOP);

        Intent intentLast = new Intent(this, RadioService.class);
        intentLast.setAction(RadioInfo.SERVICE_MEDIAPLAYER_LAST);

        Intent intentNext = new Intent(this, RadioService.class);
        intentNext.setAction(RadioInfo.SERVICE_MEDIAPLAYER_NEXT);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_radio);
//        remoteViews.setTextViewText(R.id.tv_catname, catname);
        remoteViews.setTextViewText(R.id.tv_title, getString(tvBean.getTitleResorceId()));
        remoteViews.setOnClickPendingIntent(R.id.bt_close, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentCloseAndStop, 0));
        remoteViews.setOnClickPendingIntent(R.id.bt_stop, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentStop, 0));
        remoteViews.setOnClickPendingIntent(R.id.bt_last, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentLast, 0));
        remoteViews.setOnClickPendingIntent(R.id.bt_next, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentNext, 0));

//        Intent intent = new Intent(getBaseContext(), RadioDetailActivity_.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intent, 0);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getString(R.string.app_name))
                .setContent(remoteViews);
        notification = mBuilder.build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification.bigContentView = remoteViews;
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
        startForeground(RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, notification);

    }

    public void removeNotification() {
        stopForeground(true);
    }

    private void resetNotifyTitle() {
        if (notification != null) {
            notification.contentView.setTextViewText(R.id.tv_title, getString(tvBean.getTitleResorceId()));
            mNotificationManager.notify(RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, notification);
        }
    }

    private void resetNotifyButton(String action) {
        Intent intentStop = new Intent(this, RadioService.class);
        intentStop.setAction(RadioInfo.SERVICE_MEDIAPLAYER_STOP);
        Intent intentPlay = new Intent(this, RadioService.class);
        intentPlay.setAction(RadioInfo.SERVICE_MEDIAPLAYER_PLAY);
        if (action.equals(RadioInfo.SERVICE_MEDIAPLAYER_PLAY) || action.equals(RadioInfo.SERVICE_MEDIAPLAYER_LAST) || action.equals(RadioInfo.SERVICE_MEDIAPLAYER_NEXT)) {
            notification.contentView.setOnClickPendingIntent(R.id.bt_stop, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentStop, 0));
            notification.contentView.setImageViewResource(R.id.bt_stop, android.R.drawable.ic_media_pause);
            mNotificationManager.notify(RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, notification);
        } else if (action.equals(RadioInfo.SERVICE_MEDIAPLAYER_STOP)) {
            notification.contentView.setOnClickPendingIntent(R.id.bt_stop, PendingIntent.getService(this, RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, intentPlay, 0));
            notification.contentView.setImageViewResource(R.id.bt_stop, android.R.drawable.ic_media_play);
            mNotificationManager.notify(RadioInfo.ID_NOTIFICATION_SERVICE_RADIO, notification);
        }
    }

    public void stopMediaPlayer() {
        setRunning(false);
        try {
            if (mMediaPlayer != null) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }
            }
            sendBroadcastEventStatus(RadioInfo.STATUS_STOP);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void reStartMediaPlayer() {
        if (mMediaPlayer != null) {
            setRunning(true);
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.reset();
            try {
                mMediaPlayer.setDataSource(tvBean.getUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.prepareAsync();
        }
    }

    public void stopAndCloseMediaPlayer() {
        setRunning(false);
        try {
            if (mMediaPlayer != null) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }
                mMediaPlayer.reset();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
            sendBroadcastEventStatus(RadioInfo.STATUS_STOP);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(TAG, " stopMediaPlayer => " + ex.getMessage());
        }
    }

    public void sendBroadcastEventStatus(String status) {
//        Log.i(TAG, "sendBroadcastEventStatus");
        this.status = status;
        Intent intent = new Intent(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS);
        intent.putExtra(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS, status);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    public void sendBroadCastEventValues(String type, String value) {
        Log.i(TAG, "sendBroadCastEventValues");
        Intent intent = new Intent(RadioInfo.RECEIVER_MEDIAPLAYER_CONTENT);
        intent.putExtra(type, value);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
